import 'package:flutter/material.dart';
import 'package:nav_router/nav_router.dart';

const APP_BAR_HEIGHT = 48.0;
abstract class BasePageState<T extends StatefulWidget> extends State<T> with AutomaticKeepAliveClientMixin {
  _AppBarController appBarController = _AppBarController();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      extendBodyBehindAppBar: appBarController.extendBodyBehindAppBar,
      appBar: appBarController.visible ? PreferredSize(
        preferredSize: Size.fromHeight(APP_BAR_HEIGHT),
        child: buildAppBar(context),
      ) : null,
      body: buildBody(context),
      bottomNavigationBar: buildBottomNavigationBar(context),
    );
  }

  Widget buildAppBar(BuildContext context) {
    return AppBar(
      centerTitle: true,
      elevation: 0,
      title: Text(appBarController.title),
      actions: appBarController.actions,
      bottom: appBarController.bottom,
    );
  }

  Widget buildBody(BuildContext context);

  Widget buildBottomNavigationBar(BuildContext context) {
    return null;
  }

  pushPage(Widget page) {
    routePush(page);
  }

  addAppBarTextAction(String title, VoidCallback callback) {
    setState(() {
      appBarController.actions.add(_buildAction(
          Text(title, style: TextStyle(fontSize: 16, color: Colors.white)),
          callback));
    });
  }

  addAppBarImageAction(String name, VoidCallback callback) {
    setState(() {
      appBarController.actions.add(_buildAction(
          Padding(padding: EdgeInsets.all(12), child: Image.asset(name)),
          callback));
    });
  }

  removeAppBarAction(int index) {
    setState(() {
      appBarController.actions.removeAt(index);
    });
  }

  _buildAction(Widget child, VoidCallback callback) {
    return SizedBox(
        width: APP_BAR_HEIGHT,
        child: InkWell(
          borderRadius: BorderRadius.circular(APP_BAR_HEIGHT / 2),
          child: Center(
            child: child,
          ),
          onTap: callback,
        ));
  }

  @override
  bool get wantKeepAlive => false;
}

class _AppBarController {
  String title;
  bool visible = true;
  bool extendBodyBehindAppBar = false;
  List<Widget> actions = List();
  PreferredSizeWidget bottom;
}
